Writing data to a file

Problem

You want to write data to a file.

Solution

Writing to a delimited text file

The easiest way to do this is to use write.csv(). By default, write.csv() includes row names, but these are usually unnecessary and may cause confusion.

# A sample data frame
data <- read.table(header=T, con <- textConnection('
 subject sex size
       1   M    7
       2   F    NA
       3   F    9
       4   M   11
 '))
close(con)

# Write to a file, suppress row names
write.csv(data, "data.csv", row.names=FALSE)

# Same, except that instead of "NA", output blank cells
write.csv(data, "data.csv", row.names=FALSE, na="")

# Use tabs, suppress row names and column names
write.table(data, "data.csv", sep="\t", row.names=FALSE, col.names=FALSE) 

Saving in R data format

Using write.csv() and write.table() will not preserve special attributes of the data structures, such as whether a column is a character type or factor, or the order of levels in factors. In order to do that, it should be written out in a special format for R.

# Save in a text format that can be easily loaded in R
dump("data", "data.Rdmpd")
# To load the data again: 
source("data.Rdmpd")

# Saving in R binary format which is more compact
save("data", file="data.RData")
# To load the data again:
load("data.RData")

Saving in SPSS format